<template>
  <div id="flowDefResultDiv">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" :disabled="isEmpty(flowNo)" @click="findFlowDefResultList"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="isEmpty(flowNo)" @click="addFlowDefResult"></vxe-button>
        <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="isEmpty(flowNo)" @click="saveFlowDefResultList"></vxe-button>
        <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="isEmpty(flowNo)" @click="deleteFlowDefResult"></vxe-button>
      </template>
    </vxe-toolbar>

    <div class="tableBox">
      <vxe-table ref="flowDefResultTableRef" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="bacFlowDefResultList" :loading="rloading" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
        <vxe-column type="checkbox" width="30"></vxe-column>
        <vxe-column field="defNo" title="编号" width="200" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.defNo" placeholder="" type="text"></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="defNa" title="名称" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.defNa" @click="dblclickresult(row)" placeholder="" type="text"></vxe-input>
          </template>
        </vxe-column>

        <vxe-column field="flowNodes" title="流程节点" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-select v-model="row.flowNodes" multiple placeholder="请选择">
              <vxe-option v-for="option in flowNodeList" :key="option.nodeCode" :value="option.nodeCode" :label="option.nodeName"></vxe-option>
            </vxe-select>
          </template>
          <template #default="{ row }">
            {{ formatFlowNodeNas(row.flowNodes) }}
          </template>
        </vxe-column>

        <vxe-column field="seq" title="序号" width="150" :edit-render="{}">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input v-model="row.seq" type="number"></vxe-input>
          </template>
        </vxe-column>
      </vxe-table>
    </div>

    <vxe-modal v-model="bloodCulResultModal" width="35vw" height="35vh" show-footer :mask="false">
      <template #title>
        <span>结果内容</span>
      </template>
      <template #default>
        <div class="form-panel">
          <vxe-form :data="formData" title-width="80">
            <vxe-form-item title="" span="24">
              <template #default="{ data }">
                <el-input id="formulaTextRefId" ref="formulaTextRef" type="textarea" v-model="data.defNa" ></el-input>

              </template>
            </vxe-form-item>

          </vxe-form>
        </div>
        <div class="grid col-4">
          <div class="margin-bottom-xs">
            <el-button class="button-blue margin-lr-xs cu-item" @click="actionBtnClick('[day]')">天</el-button>
          </div>
        </div>
      </template>
      <template #footer>
        <vxe-button @click="bloodCulResultModal = false">关闭</vxe-button>
        <vxe-button type="text" class="button-blue margin-left-sm" @click="confirmTextResult" content="确定"></vxe-button>
      </template>
    </vxe-modal>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
defineExpose({ initPage });
let flowNo = null;

let bacFlowDefResultList: any = reactive([]);
let flowNodeList = reactive([]);

let rloading = ref(false);


// 格式化显示选中的 nodeCode
const formatFlowNodeNas = (codes: string[]) => {
  if (!codes || codes.length === 0){
    return '';
  }
  let names=[];
  for (const code of codes) {
    const option = flowNodeList.find(option => option.nodeCode === code);
    if (option) {
      names.push(option.nodeName);
    }
  }
  return names.join(',');
};


function initPage(row: any) {
  flowNo = row;
  findFlowDefResultList();
  findAntibioticsDictPageList();
}
// 获取检验仪器表格数据
function findAntibioticsDictPageList() {
  flowNodeList.length = 0;
  if (isEmpty(flowNo)) {
    return;
  }
  const url = '/api/bac/bac-work-flow/findBacWorkFlowNodeDictList';
  proxy.$http
      .get(url, {
        params: {
          settingId: flowNo
        }
      })
      .then((res: any) => {
        flowNodeList.push(...res.data.workFlowList);
      })
      .catch((err: any) => {
        VxeMessage('搜索流程节点字典列表异常', VxeNotifyType.error);
      });
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findFlowDefResultList() {
  rloading.value = true;
  bacFlowDefResultList.length = 0; //放入数据前清空数据
  if (isEmpty(flowNo)) {
    rloading.value = false;
    return;
  }
  const url = '/api/bac/flowDefResult/findFlowDefResultList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { flowNo: flowNo }
    })
    .then((res: any) => {
      bacFlowDefResultList.push(...res.data);
      if (bacFlowDefResultList.length>0){
        bacFlowDefResultList.forEach((item: any) => {
          if (!isEmpty(item.flowNodes)){
            item.flowNodes = item.flowNodes.split(',');
          }
        });
      }
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}

function addFlowDefResult() {
  if (isEmpty(flowNo)) {
    VxeMessage('请选择方案', VxeNotifyType.error);
  } else {
    const record: any = {
      id: '',
      flowNo: flowNo,
      defNo: '',
      defNa: '',
      inputCode: '',
      seq: 1
    };
    bacFlowDefResultList.push(record);
  }
}

// 左侧保存
async function saveFlowDefResultList() {
  if (isEmpty(flowNo)) {
    VxeMessage('请选择仪器', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.flowDefResultTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = bacFlowDefResultList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateDefResults = [] as any[];
      updateRecords.forEach((e: any) => {
        const iIAppraise: any = {
          id: e.id,
          flowNo: e.flowNo,
          defNo: e.defNo,
          defNa: e.defNa,
          seq: e.seq,
          inputCode: e.inputCode,
          flowNodes: e.flowNodes.join(',')
        };

        sveOrupdateDefResults.push(iIAppraise);
      });
      InsertRecords.forEach((e: any) => {
        const iIAppraise: any = {
          id: e.id,
          flowNo: e.flowNo,
          defNo: e.defNo,
          defNa: e.defNa,
          seq: e.seq,
          inputCode: e.inputCode,
          flowNodes: e.flowNodes.join(',')
        };
        sveOrupdateDefResults.push(iIAppraise);
      });

      if (sveOrupdateDefResults.length > 0) {
        const url = '/api/bac/flowDefResult/saveOrUpdateFlowDefResult';
        const obj: any = {};
        obj.flowDefResultList = sveOrupdateDefResults;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            setTimeout(() => {
              findFlowDefResultList();
            }, 500);
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}
// 左侧删除
function deleteFlowDefResult() {
  const sltDefResults = (proxy.$refs.flowDefResultTableRef as any).getCheckboxRecords();
  if (!(sltDefResults.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delDefResultList = sltDefResults.filter((p: any) => !isEmpty(p.id));
        if (delDefResultList.length > 0) {
          const data = { flowDefResultList: delDefResultList };
          const url = '/api/bac/flowDefResult/batchDeleteFlowDefResult';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findFlowDefResultList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeResultList = sltDefResults.filter((p: any) => isEmpty(p.id));
        if (removeResultList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.flowDefResultTableRef;
          if ($Xtable) {
            for (const removeRow of removeResultList) {
              const index = bacFlowDefResultList.findIndex((item: any) => item == removeRow);
              bacFlowDefResultList.splice(index, 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
let sltFlowDefResult: any = ref({});
let formData = reactive({
  defNa: ''
});
let bloodCulResultModal = ref(false); /**培养结果弹窗 */

function dblclickresult(row: any) {
  if (isEmpty(row)) {
    sltFlowDefResult.value = {};
  } else {
    sltFlowDefResult.value = row;
    formData.defNa = row.defNa;
    bloodCulResultModal.value = true;
  }
}
function confirmTextResult() {
  sltFlowDefResult.value.defNa = formData.defNa;
  bloodCulResultModal.value = false;
}
const formulaTextRef = ref(null);

/**
 * 加 减 乘 除括号 功能按钮
 */
function actionBtnClick(e) {
  //formula.value += `${e}`;
  insertText(`${e}`);
}

function insertText(text) {
  let textarea = formulaTextRef.value?.$refs.textarea as any;
  let startPos = textarea.selectionStart; // 获取光标起始位置
  let endPos = textarea.selectionEnd; // 获取光标结束位置
  let value = isEmpty(formData.defNa) ? '' : formData.defNa;
  let newValue = value.substring(0, startPos) + text + value.substring(endPos, value.length);
  formData.defNa = newValue;

  textarea.focus(); // 将焦点设置回文本框
  proxy.$nextTick(() => {
    textarea.setSelectionRange(startPos + text.length, startPos + text.length); // 设置光标位置
  });
}
</script>

<style lang="scss" scoped>
#flowDefResultDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //右侧质控项目表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }
}
</style>
